package com.slt.android.androidexplorationart;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import static com.slt.android.androidexplorationart.UserManager.mUserId;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button btn1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn1 = (Button) findViewById(R.id.btn1);
        btn1.setOnClickListener(this);
        Log.e("jjyy" , "MainActivity1 , mUserId = " + mUserId);
        mUserId = 2;
        Log.e("jjyy" , "MainActivity2 , mUserId = " + mUserId);
        persistToFile();
    }

    /**
     * 序列化与反序列化过程
     * 尽量在新开启的线程中进行
     * 虽然在反序列化后得到的对象里面的内容和序列化之前的一样，但是并不是一个对象。
     */
    private void persistToFile() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                File dir = new File(MyConstants.CHAPTER_2_PATH);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File cachedFile = new File(MyConstants.CACHE_FILE_PATH);

                try {
                    User mUser = new User(1 , "yangqingran" , true);
                    //序列化过程
                    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(cachedFile));
                    oos.writeObject(mUser);
                    oos.close();

                    //反序列化过程
                    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(cachedFile));
                    User mUser2 = (User) ois.readObject();
                    ois.close();

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void jumpSecondActivity(){
        Intent intent = new Intent(this , SecondActivity.class);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        jumpSecondActivity();
    }
}
